import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:laoba_menu/views/category/CategoryList.dart';
import 'dart:convert';
import './Data.dart';

class Lists extends StatefulWidget {
  @override
  ListsState createState() => new ListsState();
}

class ListsState extends State<Lists> {
  Dio dio = Dio();
  Response response;
  List dataList = [];

  Future getData() async {
    final String url = 'http://127.0.0.1:7001/category/getAll';
    final res = await dio.get(url);
    var data = jsonDecode(res.toString());
    dataList = data['data']
        .map((i) => CategoryList.fromJson(i.cast<String, dynamic>()))
        .toList();
    setState(() {
      getWidgetList();
    });
  }

  @override
  initState() {
    super.initState();
    getData();
  }

  List<Widget> getWidgetList() {
    return dataList.map((item) => getItemContainer(item)).toList();
  }

  Widget getItemContainer(item) {
    return GestureDetector(
      child: Container(
        decoration: ShapeDecoration(
            image: DecorationImage(
                image: NetworkImage('${item.cover}'), fit: BoxFit.cover),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadiusDirectional.circular(20))),
        width: double.maxFinite,
        height: 200,
        child: Align(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                "${item.name}",
                textAlign: TextAlign.end,
                style: TextStyle(
                    height: 3,
                    color: Colors.white,
                    fontSize: 50,
                    fontWeight: FontWeight.bold),
              ),
              Text(
                "${item.desc}",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold),
              )
            ],
          ),
          alignment: Alignment.center,
        ),
      ),
      onTap: () => jumpMaterialPage(item.id, item.name),
    );
  }

  jumpMaterialPage(int id, String name) {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return CategoryListPage(id: id, name: name);
    }));
  }

  Future<String> mockNetworkData() async {
    return Future.delayed(Duration(seconds: 1), () => "两秒钟loading");
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: FutureBuilder<String>(
            future: mockNetworkData(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              // 请求已结束
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  // 请求失败，显示错误
                  return Text("Error: ${snapshot.error}");
                } else {
                  // 请求成功，显示数据
                  return GridView.count(
                    shrinkWrap: true,
                    //水平子Widget之间间距
                    crossAxisSpacing: 10.0,
                    //垂直子Widget之间间距
                    mainAxisSpacing: 30.0,
                    //GridView内边距
                    padding: EdgeInsets.all(10.0),
                    //一行的Widget数量
                    crossAxisCount: 1,
                    childAspectRatio: 1,
                    //子Widget列表
                    children: dataList.length > 0
                        ? getWidgetList()
                        : Center(child: Text("暂无数据")),
                    physics: new NeverScrollableScrollPhysics(),
                  );
                }
              } else {
                // 请求未结束，显示loading
                return CircularProgressIndicator();
              }
            }));
  }
}
